import { useParams } from "@solidjs/router";
import { createResource, createSignal } from "solid-js";
import { useCartContext } from "../context/CartContext";

const fetchProduct = async (id ) => {
    const responce = await fetch('http://localhost:4000/products/' + id)

    return responce.json();
}



export default function Product(){
    const params = useParams()

    const [product] = createResource(params.id, fetchProduct)
    const [quantity, setQuantity] = createSignal(1)

    const {items, setItems} = useCartContext();

    const [adding, setAdding] = createSignal(false)

    const addProduct = () => {
        setAdding(true)
        setTimeout(() => setAdding(false), 2000)

        // check if product exists
        const exists = items.find(p => p.id === product().id)
        if(exists)
            setItems(p => p.id === product().id, "quantity", q => q + quantity())
        else
            setItems([...items, {...product(), quantity: quantity()}])
    }

    const decrement = () => {
        if(quantity() > 1)
            setQuantity(q => q - 1)
    }
    const increment = () => {
        setQuantity(q => q + 1)
    }
    return(
        <div class="my-7">
            <Show when={product()} fallback={<p>Loading...</p>}>
                <div class="grid grid-cols-5 gap-7">
                    <div class="col-span-2">
                        <img class="rounded-md" src={product().img} alt="product image"/>
                    </div>
                    <div class="col-span-3">
                        <h2 class="text-3xl font-bold mb-7">{product().title}</h2>
                        <p>{product().description}</p>
                        <p class="my-7 text-2xl">Only {product().price}$</p>

                        <div class="my-4 bg-amber-400 w-max rounded-md shadow-md" disabled={adding()}>
                            <button class="px-3 py-1 text-bold text-2xl" onClick={() => decrement()} disabled={adding()}>-</button>
                            <p class="px-2 border-x-2 text-bold text-2xl border-amber-500 inline-block">{quantity()}</p>
                            <button class="pr-3 pl-2 py-1  text-bold text-2xl" onClick={() => increment()} disabled={adding()}>+</button>
                        </div>

                        <button class="btn" onClick={addProduct} disabled={adding()}>Add to Cart</button>

                        <Show when={adding()}>
                            <div class="m-2 p-2 border-amber-500 border-2 rounded-md inline-block">
                                {product().title} was added to the cart!
                            </div>
                        </Show>
                    </div>
                </div>
            </Show>
        </div>
    );
}